package org.example.JUC.pool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class PoolTool {
    
    public static ThreadPoolExecutor createPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, int queueSize, String threadNamePrefix, RejectedExecutionHandler rejectedExecutionHandler){
        return new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,new LinkedBlockingQueue<Runnable>(queueSize),new NameThreadFactory(threadNamePrefix),rejectedExecutionHandler !=null? rejectedExecutionHandler:new ThreadPoolExecutor.AbortPolicy());
        
    }

    static class NameThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber=new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber=new AtomicInteger(1);
        private final String namePrefix;

        NameThreadFactory(String threadNamePrefix) {
            SecurityManager s=System.getSecurityManager();
            group =(s!=null)? s.getThreadGroup():
                    Thread.currentThread().getThreadGroup();
            this.namePrefix=threadNamePrefix !=null?threadNamePrefix :"Pool"
                    +"-"+
                    poolNumber.getAndIncrement()+
                    "-thread-";
        }

        public Thread newThread(Runnable r){
            Thread t=new Thread(group,r,namePrefix+threadNumber.getAndIncrement(),0);
            if(t.isDaemon())
                t.setDaemon(false);
            if(t.getPriority()!=Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
